package com.example.myapplication.utils

import android.os.Handler
import android.os.Message
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import kotlin.concurrent.thread

object NetUtils {
    private val ip = "http://192.168.0.103:8080"
    fun request(
        url: String,
        requestBody: RequestBody? = null,
        headers: Headers? = null,
        handler: Handler
    ) {
        thread {
            val request = if (requestBody == null) {
                if (headers == null) {
                    Request.Builder().url(ip + url).get().build()
                } else {
                    Request.Builder().headers(headers).url(ip + url).get().build()
                }
            } else {
                if (headers == null) {
                    Request.Builder().url(ip + url).post(requestBody).build()
                } else {
                    Request.Builder().headers(headers).url(ip + url).post(requestBody).build()
                }
            }
            val client = OkHttpClient.Builder().build()
            val response = client.newCall(request).execute()
            handler.sendMessage(Message.obtain().apply {
                obj = response.body?.string()
            })
        }
    }
}